/**
 * <Table
 *   // 配置ref用于调用父组件方法获取数据
 *   ref={tableRef}
 *
 *   // getData 接口函数获取数据，必须返回一个axios Promise 同时处理好数据
 *   getTableData={getData}
 *
 *   columns={tableColumns}
 * />
 */
import React, { useEffect } from 'react'
import './style.scss'
import { Table } from 'antd'
import { TableProps } from 'rc-table/lib/Table'
import { AxiosPromise } from 'axios'
import useKeepState from 'use-keep-state'
import ActionPanel from './actionpanel'
import useDebounceFn from '../../hooks/useDebounceFn'

interface Props extends TableProps {
  getTableData: (data: any) => AxiosPromise
  onTableChange?: (pagination: any, filters: any, sorter: any) => void
  onDelete?: (id: string) => AxiosPromise
  onAdd?: () => void
  [key: string]: any
}

interface State {
  scrollY: number
  tableDataSource: any[]
  isLoading: boolean
  pagination: {
    [key: string]: any
  }
  selectedRowKeys: string[]
  columns: any[]
}

const DEFAULT_PAGE_SIZE = 50
const initialState: State = {
  scrollY: 0,
  tableDataSource: [],
  isLoading: false,
  pagination: {
    current: 1,
    pageSize: DEFAULT_PAGE_SIZE,
    showSizeChanger: true,
    total: 0,
    pageSizeOptions: ['30', '50', '70', '100', '200'],
  },
  selectedRowKeys: [],
  columns: [],
}

function showTotal(total: number) {
  return `共有${total}条`
}

// selectedRowKeys 控制表格每行前的选中框
const TableFC: React.FC<Props> = function ({
  getTableData,
  onTableChange,
  onDelete,
  onAdd,
  forwardedRef: tableRef, // 组件标签传过来的prop
  columns,
  rowSelection: rowSelectionFromParent,
}: Props) {
  let rowSelection: any = rowSelectionFromParent || undefined
  const showRowSelection: any = onDelete
  // 与react的useState不同，useKeepState的setState只需传入包含要更新的属性的对象即可，不用合并之前的state
  const [state, setState] = useKeepState(initialState)
  // 创建一个防抖函数
  const { run: getData } = useDebounceFn(
    () => {
      setState({ isLoading: true })
      const { pageNo, pageSize } = tableRef.current
      // 调用父组件函数获取数据
      getTableData({
        pageNo: pageNo - 1,
        pageSize,
      })
        .then(res => {
          if (res?.data?.success) {
            setState({
              pagination: {
                ...state.pagination,
                total: res.data.data.count,
                pageSize,
              },
              tableDataSource: res.data.data.rows,
            })
          }
        })
        .finally(() => {
          setState({ isLoading: false })
        })
    },
    { maxWait: 500, leading: true },
  )

  function onChange(pagination: any, filters: any, sorter: any) {
    const pageNo = pagination.current
    const pageSize = pagination.pageSize
    setState({
      pagination: {
        ...state.pagination,
        pageNo,
        pageSize,
      },
    })
    tableRef.current.pageNo = pageNo
    tableRef.current.pageSize = pageSize
    onTableChange?.(pagination, filters, sorter)
    setTimeout(() => {
      getData()
    }, 0)
  }

  function handleDelete() {
    if (!onDelete) return null
    const selectedRowKeys = state.selectedRowKeys.join(',')
    onDelete(selectedRowKeys).then(res => {
      if (res.data.success) {
        setState({ selectedRowKeys: [] })
        getData()
      }
    })
  }
  if (showRowSelection) {
    rowSelection = {
      onChange: function (selectedRowKeys: any[]) {
        setState({ selectedRowKeys })
      },
    }
  }

  useEffect(() => {
    if (!tableRef.current) {
      tableRef.current = {}
    }
    // 新增方法给父组件调用
    tableRef.current.getTableData = getData
  }, [tableRef])

  useEffect(() => {
    tableRef.current.pageNo = 1
    tableRef.current.pageSize = DEFAULT_PAGE_SIZE
  }, [tableRef])

  useEffect(() => {
    // 设置表格的滚动区域的高度
    const tableEl = document.querySelector('.ant-table-wrapper')
    tableEl && setState({ scrollY: tableEl.clientHeight - 120 })
  }, [])

  // "消息中心"测试数据
  // const messageData = [
  //   {
  //     // Table组件默认会把id字段作为
  //     id: 123,
  //     content:
  //       '性命精彩起点，从懵懂到老练，从幼稚到成熟，从浅薄到深沉，一路风雨磕碰，走走停停，自古少年壮志起征程，青春热血洒后生，中年稳中求上进，年老与子夕阳共。青春，赋予性命的活力，干劲，拼劲，闯劲，自有初生牛犊不怕虎，偏向虎山行。青春，性命精彩所在，令多少垂暮之年不胜感慨与唏嘘。自由自在，青春快乐，走过的印记，总不免让人因不去珍惜而遗憾或怀念。想想人生一程，但是，年少多轻狂，青春无价宝，不惑皆烦忧，老来安康求。',
  //     hasRead: false,
  //     createdAt: '2021-03-24 21:55',
  //     title: '生活',
  //   },
  //   {
  //     // Table组件默认会把id字段作为
  //     id: 123241,
  //     content:
  //       '性命精彩起点，从懵懂到老练，从幼稚到成熟，从浅薄到深沉，一路风雨磕碰，走走停停，自古少年壮志起征程，青春热血洒后生，中年稳中求上进，年老与子夕阳共。青春，赋予性命的活力，干劲，拼劲，闯劲，自有初生牛犊不怕虎，偏向虎山行。青春，性命精彩所在，令多少垂暮之年不胜感慨与唏嘘。自由自在，青春快乐，走过的印记，总不免让人因不去珍惜而遗憾或怀念。想想人生一程，但是，年少多轻狂，青春无价宝，不惑皆烦忧，老来安康求。',
  //     hasRead: false,
  //     createdAt: '2021-03-24 21:55',
  //     title: '生活',
  //   },
  // ]

  return (
    <>
      {/* 新增，批量删除 */}
      <ActionPanel
        selectedRowKeys={state.selectedRowKeys}
        onDelete={onDelete && handleDelete}
        onAdd={onAdd}
      />
      <Table
        rowKey="id"
        loading={state.isLoading}
        columns={columns as any[]}
        dataSource={state.tableDataSource}
        // dataSource={messageData}
        scroll={{ x: 1200, y: state.scrollY }}
        showHeader={state.tableDataSource.length}
        onChange={onChange}
        rowSelection={rowSelection}
        pagination={{
          ...state.pagination,
          size: 'small',
          showTotal,
        }}
      ></Table>
    </>
  )
}

const forwardedTable = React.forwardRef((props: any, ref) => (
  <TableFC {...props} forwardedRef={ref} />
))

export default React.memo(forwardedTable)
